#include "userequest.h"
#include <QNetworkReply>
#include <QJsonDocument>

UserRequest::UserRequest(QObject *parent)
    : QObject{parent}
{
    manager = new QNetworkAccessManager(this);
    connect(manager,&QNetworkAccessManager::finished,this,&UserRequest::onFinished);
}

//登录接口
void UserRequest::login(const QString &data)
{
    QNetworkRequest request(QUrl("http://"+ip+":"+port+"/user/login"));
    request.setRawHeader("Content-Type","application/json");
    manager->post(request,data.toUtf8());
}

//注册接口
void UserRequest::reg(const QString &data)
{
    QNetworkRequest request(QUrl("http://"+ip+":9000/user/registered"));
    request.setRawHeader("Content-Type","application/json");
    manager->post(request,data.toUtf8());
}

//个人信息的查询接口
void UserRequest::SelfInformation(const int &id)
{
    QNetworkRequest request(QUrl("http://"+ip+":9000/user/get?id="+QString::number(id)));
    request.setRawHeader("Content-Type","application/json");
    manager->get(request);
}

//修改个人信息接口
void UserRequest::UpdateSelfInformation(const QString &data)
{
    QNetworkRequest request(QUrl("http://"+ip+":9000/user/"));
    request.setRawHeader("Content-Type","application/json");
    manager->post(request,data.toUtf8());
}

QString UserRequest::getUri(const QString &url)
{
    int l1 = url.length();
    int n;
    for(int i=0;i<l1;i++){
        if(url[i]=='?'){
            n = i;
            break;
        }
    }
    int l2 = url.lastIndexOf(":") + 5;
    return url.mid(l2,n - l2);
}

//用户请求响应接口
void UserRequest::onFinished(QNetworkReply *reply)
{
    QString url = reply->url().toString();
    QString uri = getUri(url);
    QByteArray data = reply->readAll();
    if(data.length() == 0){
        qDebug()<<"服务器暂时坏了";
        return;
    }
    QJsonDocument doc = QJsonDocument::fromJson(data);
    QJsonObject obj = doc.object();
    if(uri == "/user/login"){
        emit loginFinished(obj);
    }else if(uri == "/user/registered"){
        emit regFinished(obj);
    }else if(uri == "/user/get"){
        emit(selfCheckFinished(obj));
    }else if(uri == "/user/update"){
        emit(updateFinished(obj));
    }
}
